<?php


class TopicController extends Controller
{

  /**
   * 发帖子
   */
  public function actionPost()
  {
    $this->checkGuest();
    if (Yii::app()->request->isPostRequest) {
      $result = TopicService::instance()->post($this->filter($_POST));
      if (is_numeric($result) && $result > 0) {
        $this->success('发表成功!', Yii::app()->createUrl('topic/view', array('id' => $result)));
      } else {
        $this->error($this->getError($result), 200);
      }
    } else {
      if (!$this->isMobile()) {
        $this->initEditor();
      }
      $this->render('/site/topic/post');
    }
  }

  /**
   * 查看帖子
   * @param int $id
   */
  public function actionView($id = 0)
  {
    $data = TopicService::instance()->get($id);
    if (empty($data)) {
      $this->error('帖子不存在!', 404);
    }
    TopicService::instance()->plus($id);
    $threads = TopicService::instance()->getThreadList($id, 10, false);
    $this->render('/site/topic/view', array(
        'data' => $data,
        'threads' => $threads
    ));
  }

  /**
   * 回帖子
   */
  public function actionReply()
  {
    if (Yii::app()->request->isPostRequest) {
      $result = TopicService::instance()->reply($this->filter($_POST));
      if ($result === true) {
        $this->success('回复成功!', Yii::app()->createUrl('topic/view', array('id' => $_POST['topic_id'])));
      } else {
        $this->error($this->getError($result));
      }
    } else {
      $this->error('非法请求!', 403);
    }
  }


  /**
   * 帖子列表
   * @param string $keywords
   */
  public function actionList($keywords='')
  {
   $data = TopicService::instance()->getTopicList(10,true,$keywords);
    $this->render('/site/topic/list',array(
      'data'=>$data
    ));
  }
}